﻿/*
 *  Copyright 2012 Cloudbase Solutions Srl
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the Microsoft Public License (Ms-PL).  
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Security;
using Microsoft.Web.Management.Server;
using Microsoft.Web.Management.Client;
using Microsoft.Web.Management.Client.Win32;
using System.Collections;
using MsdnMag;
using System.Windows.Forms;
using System.Drawing;
using System.Resources;
using System.Globalization;
using System.Net;
using Cloudbase.Iis.HostsFileManager.Common;

namespace Cloudbase.Iis.HostsFileManager.Client
{
    internal class HostsFileModule : Module
    {
        private LocalCbtHook hook;
        private bool formActivated;
        private IDictionary<string, string> formCaptions;
        private IHostsFileModuleService svc;

        public HostsFileModule()
        {
            hook = new LocalCbtHook();
            hook.WindowActivated += hook_WindowActivated;
        }

        protected override bool IsPageEnabled(ModulePageInfo pageInfo)
        {
            Connection service = (Connection)this.GetService(typeof(Connection));
            return (service.ConfigurationPath.PathType == ConfigurationPathType.Server);
        }

        void hook_WindowActivated(object sender, CbtEventArgs e)
        {
            CheckForm(e);
        }

        private void CheckForm(CbtEventArgs e)
        {
            if (!formActivated && formCaptions.ContainsKey(e.Title))
            {
                Form f = (Form)Form.FromHandle(e.Handle);
                if (f != null && f.GetType().FullName.Equals(formCaptions[e.Title]))
                {
                    formActivated = true;
                    f.FormClosed += f_FormClosed;

                    var tbHostHeader = f.Controls.Find("_hostHeaderTextBox", true)[0];

                    var coll = tbHostHeader.Parent.Controls;

                    /*                    
                    foreach (Control c in coll)
                    {
                        System.Diagnostics.Debug.WriteLine(c.GetType().Name);
                        System.Diagnostics.Debug.WriteLine(c.Name);
                        System.Diagnostics.Debug.WriteLine(c.Location);
                        System.Diagnostics.Debug.WriteLine(c.Size);
                    }
                    */
                    int y = tbHostHeader.Location.Y;
                    int x = coll.Find("_portTextBox", false)[0].Location.X;

                    string caption = (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor < 2) ? StringResource.AddToHostsFileIIS7 : StringResource.AddToHostsFileIIS8;

                    CheckBox cb = new CheckBox();
                    cb.Name = "_cbAddToHostsFile";
                    cb.Text = caption;
                    cb.Location = new Point(x, y);
                    cb.Size = new Size(150, 19);
                    coll.Add(cb);
                }
            }
        }

        void f_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (formActivated)
            {
                formActivated = false;

                try
                {
                    var f = (Form)sender;
                    if (f.DialogResult == DialogResult.OK)
                    {
                        CheckBox cb = (CheckBox)f.Controls.Find("_cbAddToHostsFile", true)[0];
                        TextBox tbHostHeader = (TextBox)f.Controls.Find("_hostHeaderTextBox", true)[0];
                        string hostHeader = tbHostHeader.Text.Trim();

                        if (cb.Checked && hostHeader.Length > 0)
                            svc.AddHost(hostHeader, IPAddress.Parse("127.0.0.1"), null);
                    }
                }
                catch (Exception ex)
                {
                    // Don't propagate exceptions
                    MessageBox.Show(null, ex.Message, StringResource.HostsFileSavingError, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        protected override object GetService(Type serviceType)
        {
            return base.GetService(serviceType);
        }

        protected override void Dispose()
        {
            hook.Uninstall();
            base.Dispose();          
        }

        protected override void Initialize(IServiceProvider serviceProvider, ModuleInfo moduleInfo)
        {
            base.Initialize(serviceProvider, moduleInfo);

            Connection con = (Connection)serviceProvider.GetService(typeof(Connection));
            svc = (IHostsFileModuleService)con.CreateProxy(this, typeof(HostsFileModuleServiceProxy));

            IControlPanel controlPanel = (IControlPanel)GetService(typeof(IControlPanel));
            controlPanel.RegisterPage(ControlPanelCategoryInfo.Management, 
                                      new ModulePageInfo(this, 
                                                         typeof(HostsFileModuleListPage), 
                                                         StringResource.HostsFileModuleTitle, 
                                                         StringResource.HostsFileModuleDescription));

            LoadLocalizedFormCaptions();
            hook.Install();
        }

        private void LoadLocalizedFormCaptions()
        {
            formCaptions = new Dictionary<string, string>();

            foreach (var a2 in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (a2.GetName().Name.Equals("Microsoft.Web.Management.IisClient"))
                {
                    var rm = new ResourceManager("Microsoft.Web.Management.Iis.Resources", a2);
                    using (var rs = rm.GetResourceSet(CultureInfo.CurrentUICulture, true, true))
                    {
                        formCaptions[rs.GetString("WebSitesCreateWebSiteWizardFormNewTitle", false)] = "Microsoft.Web.Management.Iis.WebObjects.WebSites.CreateSiteTaskForm";
                        formCaptions[rs.GetString("WebSitesEditWebSiteBindingsWizardFormNewCaption", false)] = "Microsoft.Web.Management.Iis.WebObjects.WebSites.EditSiteBindingTaskForm";
                        formCaptions[rs.GetString("WebSitesEditWebSiteBindingsWizardFormModifyCaption", false)] = "Microsoft.Web.Management.Iis.WebObjects.WebSites.EditSiteBindingTaskForm";
                    }
                    break;
                }
            }
        }
    }
}
